"""
关于对话框组件 - 完整修复版本
"""

import tkinter as tk
from tkinter import ttk
import sys
import platform
from datetime import datetime


class AboutDialog:
    """关于对话框 - 完整修复版本"""

    def __init__(self, parent):
        self.parent = parent

        # 创建对话框
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("关于 - 屏幕点击和输入工具")
        self.dialog.geometry("500x400")
        self.dialog.resizable(False, False)
        self.dialog.transient(parent)
        self.dialog.grab_set()

        # 设置对话框位置（居中）
        self.dialog.update_idletasks()
        x = parent.winfo_x() + (parent.winfo_width() - self.dialog.winfo_width()) // 2
        y = parent.winfo_y() + (parent.winfo_height() - self.dialog.winfo_height()) // 2
        self.dialog.geometry(f"+{x}+{y}")

        # 设置对话框图标
        try:
            self.dialog.iconbitmap(self.get_resource_path("assets/icon.ico"))
        except:
            pass

        # 创建界面
        self.create_widgets()

        # 绑定事件
        self.bind_events()

    def get_resource_path(self, relative_path: str) -> str:
        """获取资源文件路径"""
        try:
            import os
            base_path = getattr(sys, '_MEIPASS',
                                os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
            return os.path.join(base_path, relative_path)
        except:
            return relative_path

    def create_widgets(self):
        """创建界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.dialog, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题区域
        title_frame = ttk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 20))

        # 程序图标和名称
        try:
            from PIL import Image, ImageTk
            icon_path = self.get_resource_path("assets/icon.ico")
            if icon_path:
                image = Image.open(icon_path)
                image = image.resize((64, 64), Image.Resampling.LANCZOS)
                self.logo_image = ImageTk.PhotoImage(image)
                logo_label = ttk.Label(title_frame, image=self.logo_image)
                logo_label.pack(side=tk.LEFT, padx=(0, 15))
        except:
            pass

        # 程序信息
        info_frame = ttk.Frame(title_frame)
        info_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        title_label = ttk.Label(
            info_frame,
            text="屏幕点击和输入工具",
            font=("Arial", 16, "bold")
        )
        title_label.pack(anchor=tk.W)

        version_label = ttk.Label(
            info_frame,
            text="版本 2.0.0",
            font=("Arial", 10)
        )
        version_label.pack(anchor=tk.W, pady=(2, 0))

        # 描述文本
        desc_text = """一个功能强大的自动化工具，支持屏幕点击、键盘输入、
图片识别和Excel数据处理。"""

        desc_label = ttk.Label(
            main_frame,
            text=desc_text,
            justify=tk.LEFT,
            wraplength=400
        )
        desc_label.pack(fill=tk.X, pady=(0, 20))

        # 功能列表
        features_frame = ttk.LabelFrame(main_frame, text="主要功能", padding="10")
        features_frame.pack(fill=tk.X, pady=(0, 20))

        features = [
            "✓ 智能记录鼠标位置和操作序列",
            "✓ 支持粘贴、键盘输入和图片输入",
            "✓ 完整的Excel数据处理功能",
            "✓ 可视化点编辑和管理",
            "✓ 线程安全的多任务执行",
            "✓ 完善的错误处理和用户反馈"
        ]

        for feature in features:
            feature_label = ttk.Label(
                features_frame,
                text=feature,
                justify=tk.LEFT
            )
            feature_label.pack(anchor=tk.W, pady=2)

        # 系统信息
        sysinfo_frame = ttk.LabelFrame(main_frame, text="系统信息", padding="10")
        sysinfo_frame.pack(fill=tk.X, pady=(0, 20))

        sys_info = self.get_system_info()
        for key, value in sys_info.items():
            info_frame = ttk.Frame(sysinfo_frame)
            info_frame.pack(fill=tk.X, pady=1)

            ttk.Label(
                info_frame,
                text=f"{key}:",
                font=("Arial", 9, "bold"),
                width=15
            ).pack(side=tk.LEFT)

            ttk.Label(
                info_frame,
                text=value,
                font=("Arial", 9)
            ).pack(side=tk.LEFT)

        # 版权信息
        copyright_frame = ttk.Frame(main_frame)
        copyright_frame.pack(fill=tk.X)

        copyright_text = f"© 2024 屏幕点击和输入工具项目组\n构建时间: {self.get_build_time()}"

        copyright_label = ttk.Label(
            copyright_frame,
            text=copyright_text,
            justify=tk.CENTER,
            font=("Arial", 8),
            foreground="gray"
        )
        copyright_label.pack()

        # 按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0))

        ttk.Button(
            button_frame,
            text="关闭",
            command=self.dialog.destroy
        ).pack(side=tk.RIGHT)

    def bind_events(self):
        """绑定事件"""
        self.dialog.bind('<Return>', lambda e: self.dialog.destroy())
        self.dialog.bind('<Escape>', lambda e: self.dialog.destroy())

    def get_system_info(self) -> dict:
        """获取系统信息"""
        info = {
            "Python版本": f"{platform.python_version()} ({platform.python_implementation()})",
            "操作系统": f"{platform.system()} {platform.release()}",
            "系统架构": platform.machine(),
            "处理器": platform.processor() or "未知"
        }

        # 添加内存信息（如果可用）
        try:
            import psutil
            memory = psutil.virtual_memory()
            info["总内存"] = f"{memory.total // (1024 ** 3)} GB"
            info["可用内存"] = f"{memory.available // (1024 ** 3)} GB"
        except ImportError:
            pass

        return info

    def get_build_time(self) -> str:
        """获取构建时间"""
        try:
            # 尝试从构建信息文件读取
            build_info_path = self.get_resource_path("build_info.txt")
            import os
            if os.path.exists(build_info_path):
                with open(build_info_path, 'r', encoding='utf-8') as f:
                    return f.read().strip()
        except:
            pass

        # 默认使用当前时间
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    def show(self):
        """显示对话框"""
        return self.dialog


def show_about_dialog(parent):
    """显示关于对话框"""
    dialog = AboutDialog(parent)
    dialog.show()